import router from '@/router'
import axios from 'axios'
import { ElMessage } from 'element-plus'

const instance = axios.create({

  baseURL: process.env.VUE_APP_BASE_API,
  withCredentials: true, // 跨域请求时是否需要访问凭证
  // timeout: 2000 // 请求超时时间
  headers: {
    'datasource': 'guangyin'
  }
})
/*
  2003: 密码错误
*/
instance.interceptors.response.use(
  response => {
    if (response.data instanceof Blob) {
      return response.data
    }
    const {code, message} = response.data
    if (code === 200) return response.data
    // 其余返回码作为异常
    ElMessage({type: 'error', message: message})
    return Promise.reject(response.data)
  },
  error => {
    const response = error.response
    if (response.status != null && response.status === 401) {
      ElMessage({type: 'error', message: '用户未认证，请登录后重试'})
      router.push('/login')
    }
    if (response.status != null && response.status === 403) {
      ElMessage({type: 'error', message: '用户访问权限不足'})
    }
    if (response.status != null && response.status === 400) {
      ElMessage({type: 'error', message: response.data.error})
    }
    // const { errorMessage } = error.response.data
    // if (errorMessage != '' && errorMessage != null && errorMessage != undefined) {
    //   return Promise.reject(error.response.data)
    // }
    return Promise.reject(error.response.data)
  }
)

export default instance
